package com.devMode.ProxyMode;

/**
 * 代理模式
 *
 * --远程代理：控制远程对象，将请求进行特定的编码，向不同的地址空间发送已经编码的请求（nginx）
 * --虚拟代理：根据需要创建对象的开销很大，它可以缓存实体的附加信息，以便延迟对它的访问
 * --保护代理：按权限控制对象的访问，负责检查调用者是否具有实现一个请求所必须要有的权限
 * --智能代理：取代了简单的指针，在访问一个对象的时候附加一些操作，相当于封装了指针的操作
 */

import java.net.MalformedURLException;
import java.net.URL;

/**
 * 虚拟代理的实现
 */
public class ProxyMode {
    public static void main(String[] args) throws MalformedURLException {
        String image = "http://image.png";
        URL url = new URL(image);
        HighResolutionImage highResolutionImage = new HighResolutionImage(url);
        ImageProxy imageProxy = new ImageProxy(highResolutionImage);
        imageProxy.showImage();
    }
}

interface Image{
    void showImage();
}


class HighResolutionImage implements Image{

    private URL imageUrl;
    private long startTime;
    private int width;
    private int height;

    public HighResolutionImage(URL imageUrl){
        this.imageUrl = imageUrl;
        this.startTime = System.currentTimeMillis();
        this.width = 600;
        this.height = 600;
    }

    @Override
    public void showImage() {
        System.out.println("real image : " + imageUrl);
    }

    public boolean isLoad(){
        long endTime = System.currentTimeMillis();
        return endTime - startTime > 3000;
    }

    public URL getImageUrl(){
        return this.imageUrl;
    }

    public int getWidth() {
        return width;
    }

    public int getHeight() {
        return height;
    }
}


class ImageProxy implements Image{

    private HighResolutionImage highResolutionImage;

    public ImageProxy(HighResolutionImage highResolutionImage){
        this.highResolutionImage = highResolutionImage;
    }

    @Override
    public void showImage() {
        while(!highResolutionImage.isLoad()){
            try{
                System.out.println("temp image: " + highResolutionImage.getWidth() + " --- "
                + highResolutionImage.getHeight());
                Thread.sleep(1000);
            }catch (InterruptedException e){
                e.printStackTrace();;
            }
        }
        highResolutionImage.showImage();
    }
}












